#coding:utf-8

import Image
import ImageGrab
import itertools
import operator
from pytesser import *
import autopy
import time

class Wordpic(object):
    def __init__(self):
        #打开对应英汉字典文件（以字典格式保存）
        self.dict_tx = open('wordmeans.txt', 'r').read()
        self.dt = eval(self.dict_tx)
        self.lastWord = None

    def get_hash(self, img):
        #计算图片的hash值
        image = img.convert("L")
        pixels = list(image.getdata())
        avg = sum(pixels) / len(pixels)
        return "".join(map(lambda p : "1" if p > avg else "0", pixels))

    def wordCheck(self):
        hash_title = self.get_hash(ImageGrab.grab((393, 448, 393+64, 448+64)))
        hash_title_local = self.get_hash(Image.open('flag.jpg'))

        hash_error = self.get_hash(ImageGrab.grab((743, 419, 743+72, 419+64)))
        hash_error_local = self.get_hash(Image.open('errflag.jpg'))

        this_dist = self.hamming_dist(hash_title, hash_title_local)
        err_dist = self.hamming_dist(hash_error, hash_error_local)

        #判断当前界面如果this_dist小于40表示在选择界面，err_dist界面表示回答错误界面
        #print this_dist
        if this_dist < 40:
            #print 'Word check start ...'
            word_up = self.getWordMeaning()
        elif err_dist < 50:
            self.mouseMove(0)
        else:
            pass
                        #self.mouseMove(-1)

    #计算2个图片的距离
    def hamming_dist(self, hash1, hash2):
        return sum(itertools.imap(operator.ne, hash1, hash2))

    #识别出对应位置图像成字符，把字符交给chose处理
    def getWordMeaning(self):
        pic_up = ImageGrab.grab((480,350, 480+300, 350+66))
        pic_aws1 = ImageGrab.grab((463,456, 463+362, 456+45))
        pic_aws2 = ImageGrab.grab((463,530, 463+362, 530+45))
        pic_aws3 = ImageGrab.grab((463,601, 463+362, 601+45))
        pic_aws4 = ImageGrab.grab((463,673, 463+362, 673+45))

        str_up = image_to_string(pic_up).strip().lower()

        #判断当前单词和上次识别单词相同，就不继续识别
        if str_up <> self.lastWord:
            #如果题目单词是英文，选项按中文进行识别
            if str_up.isalpha():
                eng_up = self.dt[str_up].decode('gbk') if self.dt.has_key(str_up) else ''
                chs1 = image_to_string(pic_aws1, language='chi_sim').decode('utf-8').strip()
                chs2 = image_to_string(pic_aws2, language='chi_sim').decode('utf-8').strip()
                chs3 = image_to_string(pic_aws3, language='chi_sim').decode('utf-8').strip()
                chs4 = image_to_string(pic_aws4, language='chi_sim').decode('utf-8').strip()
                print str_up, ':', eng_up
                self.chose(eng_up, (chs1, chs2, chs3, chs4))
            #如果题目单词是中文，选项按英文进行识别
            else:
                chs_up = image_to_string(pic_up, language='chi_sim').decode('utf-8').strip()
                eng1 = image_to_string(pic_aws1).strip()
                eng2 = image_to_string(pic_aws2).strip()
                eng3 = image_to_string(pic_aws3).strip()
                eng4 = image_to_string(pic_aws4).strip()

                e2c1 = self.dt[eng1].decode('gbk') if self.dt.has_key(eng1) else ''
                e2c2 = self.dt[eng2].decode('gbk') if self.dt.has_key(eng2) else ''
                e2c3 = self.dt[eng3].decode('gbk') if self.dt.has_key(eng3) else ''
                e2c4 = self.dt[eng4].decode('gbk') if self.dt.has_key(eng4) else ''
                print chs_up
                self.chose(chs_up, (e2c1, e2c2, e2c3, e2c4))
            self.lastWord = str_up
        return str_up

    #根据传入的题目和选项进行匹配选择
    def chose(self, g, chs_list):
        j, max_score = -1, 0
        same_list = None
        #替换掉题目里的特殊字符
        re_list = [u'~', u',', u'.', u';', u' ', u'a', u'V', u'v', u'i', u'n', u'【', u')', u'_', u'W', u'd', u'j', u'-', u't']
        for i in re_list:
            g = g.replace(i, '')
        print type(g)

        #判断2个字符串中相同字符，相同字符最多的为最佳答案
        for i, chsWord in enumerate(chs_list):
            print type(chsWord)
            l = [x for x in g if x in chsWord and len(x)>0]
            score = len(l) if l else 0

            if score > max_score:
                max_score = score
                j = i
                same_list = l
        #如果没有匹配上默认选最后一个
        if j ==-1:
            print '1. %s; 2. %s; 3. %s; 4. %s; Not found choice.' % (chs_list[0], chs_list[1], chs_list[2], chs_list[3])
        else:
            print '1. %s; 2. %s; 3. %s; 4. %s; choice: %s' % (chs_list[0], chs_list[1], chs_list[2], chs_list[3], chs_list[j])
            for k, v in enumerate(same_list):
                print str(k) + '.' + v,
        order = j + 1
        self.mouseMove(order)
        return order

    #通过内置固定坐标，操作鼠标对题目答案进行选择
    def mouseMove(self, p):
        if p > 0:
            pos_dt={1: (463,456), 2: (463,530), 3: (463,601), 4: (463,673)}
            autopy.mouse.move(*pos_dt[p])
            autopy.mouse.click()
            autopy.mouse.move(1200,673)
        elif p == 0:
            autopy.mouse.move(463,673)
            autopy.mouse.click()
            autopy.mouse.move(1200,673)
            print 'No answer, Choice 4!'
        elif p == -1:
            autopy.mouse.move(840,720)
            autopy.mouse.click()
            autopy.mouse.move(1200,673)            
            print 'retry click.'
            time.sleep(3)

if __name__ == '__main__':
    word = Wordpic()
    while True:
        word_tmp = word.wordCheck()




#f = open('d:\\4.txt', 'r')
#tx = f.read()
#try:
    #dt = eval(tx)
#except Exception as  e:
    #print e
    #print traceback.print_exc()

#print process.extractOne('complement', choices=dt.keys())